<template>
  <div class="container">
    <Breadcrumb :items="[$t('订单管理'), $t('对账管理'), $t('对账记录')]" />
    <a-card class="general-card">
      <template #title>
        <a-space>
          <span>{{ $t('对账记录') }}</span>
          <a-tag>{{ batchNo }}</a-tag>
        </a-space>
      </template>
      <a-row style="margin-bottom: 16px">
        <a-col :span="24" style="text-align: right">
          <a-space>
            <a-button @click="goBack">
              <template #icon>
                <icon-arrow-left />
              </template>
              {{ $t('返回') }}
            </a-button>
            <a-button type="primary" @click="viewBatchDetail">
              <template #icon>
                <icon-info-circle />
              </template>
              {{ $t('批次详情') }}
            </a-button>
            <a-button type="primary" status="success" @click="exportData">
              <template #icon>
                <icon-download />
              </template>
              {{ $t('导出记录') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #verifyStatus="{ record }">
          <a-tag :color="record.verifyStatus === 1 ? 'green' : 'red'">
            {{ record.verifyStatus === 1 ? '已匹配' : '未匹配' }}
          </a-tag>
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="viewDetail(record)">
              <template #icon><icon-eye /></template>
              {{ $t('详情') }}
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 记录详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      :title="$t('记录详情')"
      :footer="false"
      width="600px"
    >
      <a-descriptions :column="1" bordered>
        <a-descriptions-item :label="$t('批次号')">{{ currentRecord?.batchNo }}</a-descriptions-item>
        <a-descriptions-item :label="$t('平台ID')">{{ currentRecord?.platformId }}</a-descriptions-item>
        <a-descriptions-item :label="$t('订单号')">{{ currentRecord?.orderNo }}</a-descriptions-item>
        <a-descriptions-item :label="$t('设备编号')">{{ currentRecord?.pileCode }}</a-descriptions-item>
        <a-descriptions-item :label="$t('开始时间')">{{ currentRecord?.startTime }}</a-descriptions-item>
        <a-descriptions-item :label="$t('充电电量(kWh)')">{{ currentRecord?.chargingElec }}</a-descriptions-item>
        <a-descriptions-item :label="$t('核对状态')">
          <a-tag :color="currentRecord?.verifyStatus === 1 ? 'green' : 'red'">
            {{ currentRecord?.verifyStatus === 1 ? '已匹配' : '未匹配' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item v-if="currentRecord?.verifyStatus === 0" :label="$t('未匹配原因')">
          {{ currentRecord?.unmatchReason || '-' }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('创建时间')">{{ currentRecord?.createTime }}</a-descriptions-item>
        <a-descriptions-item :label="$t('更新时间')">{{ currentRecord?.updateTime }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 批次详情对话框 -->
    <a-modal
      v-model:visible="batchDetailVisible"
      :title="$t('批次详情')"
      :footer="false"
      width="600px"
    >
      <a-descriptions :column="1" bordered>
        <a-descriptions-item :label="$t('批次号')">{{ batchInfo?.batchNo }}</a-descriptions-item>
        <a-descriptions-item :label="$t('平台ID')">{{ batchInfo?.platformId }}</a-descriptions-item>
        <a-descriptions-item :label="$t('总记录数')">{{ batchInfo?.totalCount }}</a-descriptions-item>
        <a-descriptions-item :label="$t('成功记录数')" class="success-count">{{ batchInfo?.successCount }}</a-descriptions-item>
        <a-descriptions-item :label="$t('失败记录数')" class="fail-count">{{ batchInfo?.failCount }}</a-descriptions-item>
        <a-descriptions-item :label="$t('状态')">
          <a-tag :color="batchInfo?.status === 0 ? 'blue' : batchInfo?.status === 1 ? 'green' : ''">
            {{ batchInfo?.status === 0 ? '处理中' : batchInfo?.status === 1 ? '处理完成' : '-' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item :label="$t('创建时间')">{{ batchInfo?.createTime }}</a-descriptions-item>
        <a-descriptions-item :label="$t('更新时间')">{{ batchInfo?.updateTime }}</a-descriptions-item>
        <a-descriptions-item :label="$t('创建人')">{{ batchInfo?.createBy || '-' }}</a-descriptions-item>
        <a-descriptions-item :label="$t('更新人')">{{ batchInfo?.updateBy || '-' }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { getVerifyRecords, exportRecords, getVerifyBatch } from '@/api/order/reconciliation';
import type { OrderVerifyRecord, OrderVerifyBatch } from '@/api/order/reconciliation/types';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 批次号
const batchNo = ref<string>(route.query.batchNo as string);

// 加载状态
const { loading, setLoading } = useLoading();

// 详情对话框
const detailVisible = ref(false);
const currentRecord = ref<OrderVerifyRecord | null>(null);

// 批次详情
const batchDetailVisible = ref(false);
const batchInfo = ref<OrderVerifyBatch | null>(null);

// 表格列定义
const columns = computed(() => [
  {
    title: '订单号',
    dataIndex: 'orderNo',
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '平台ID',
    dataIndex: 'platformId',
    width: 120,
  },
  {
    title: '设备编号',
    dataIndex: 'pileCode',
    width: 150,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    width: 180,
  },
  {
    title: '充电电量(kWh)',
    dataIndex: 'chargingElec',
    width: 150,
  },
  {
    title: '核对状态',
    dataIndex: 'verifyStatus',
    slotName: 'verifyStatus',
    width: 120,
  },
  {
    title: '未匹配原因',
    dataIndex: 'unmatchReason',
    width: 200,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 120,
    fixed: 'right',
  },
]);

// 表格数据
const renderData = ref<OrderVerifyRecord[]>([]);

// 分页参数
const basePagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
};
const pagination = reactive({
  ...basePagination,
});

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  initLocalPagination();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  initLocalPagination();
}

// 初始化本地分页数据
function initLocalPagination() {
  const { current, pageSize } = pagination;
  const start = (current - 1) * pageSize;
  const end = start + pageSize;
  
  if (allRecords.value.length > 0) {
    renderData.value = allRecords.value.slice(start, end);
    pagination.total = allRecords.value.length;
  }
}

// 返回上一页
function goBack() {
  router.back();
}

// 导出数据
async function exportData() {
  try {
    setLoading(true);
    await exportRecords({
      batchNo: batchNo.value,
      current: 1,
      size: 9999
    });
    Message.success('导出成功');
  } catch (error) {
    console.error('导出对账记录失败:', error);
    Message.error('导出失败');
  } finally {
    setLoading(false);
  }
}

// 查看详情
function viewDetail(record: OrderVerifyRecord) {
  currentRecord.value = record;
  detailVisible.value = true;
}

// 查看批次详情
function viewBatchDetail() {
  batchDetailVisible.value = true;
}

// 所有记录数据（用于前端分页）
const allRecords = ref<OrderVerifyRecord[]>([]);

// 获取对账记录数据
async function fetchData() {
  if (!batchNo.value) {
    Message.error('批次号不能为空');
    return;
  }

  setLoading(true);
  try {
    // 获取批次信息
    const batchRes = await getVerifyBatch(batchNo.value);
    batchInfo.value = batchRes.data;
    
    // 获取记录列表
    const res = await getVerifyRecords(batchNo.value);
    allRecords.value = res.data || [];
    initLocalPagination();
  } catch (error) {
    console.error('获取对账记录失败:', error);
    Message.error('获取对账记录列表失败');
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  :deep(.arco-card-header) {
    padding: 20px;
  }
  :deep(.arco-card-body) {
    padding: 0 20px 20px 20px;
  }
}

.success-count {
  :deep(.arco-descriptions-item-value) {
    color: #52C41A;
  }
}

.fail-count {
  :deep(.arco-descriptions-item-value) {
    color: #FF4D4F;
  }
}
</style> 